const BASE_URL = 'http://192.168.11.4:5000'

// 获取access_token
function getAccessToken() {
  return wx.getStorageSync('access_token');
}

// 获取refresh_token
function getRefreshToken() {
  return wx.getStorageSync('refresh_token');
}

// 检查access_token是否过期
function isTokenExpired() {
  const token = getAccessToken();
  if (!token) return true;
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    const now = Math.floor(Date.now() / 1000);
    return payload.exp < now;
  } catch (error) {
    return true;
  }
}

// 刷新token
function refreshToken() {
  return new Promise((resolve, reject) => {
    try {
      const refreshToken = getRefreshToken();
      if (!refreshToken) {
        throw new Error('No refresh token');
      }

      wx.request({
        url: BASE_URL + '/api/refresh',
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'Authorization': 'Bearer ' + refreshToken
        },
        success: function(res) {
          if (res.data.code === 200) {
            wx.setStorageSync('access_token', res.data.data.access_token);
            resolve(res.data.data.access_token);
          } else {
            throw new Error('Token refresh failed');
          }
        },
        fail: function(error) {
          console.error('Token refresh failed:', error);
          // 清除所有token，需要重新登录
          wx.removeStorageSync('access_token');
          wx.removeStorageSync('refresh_token');
          reject(error);
        }
      });
    } catch (error) {
      reject(error);
    }
  });
}

// 主要请求函数
function request(options) {
  return new Promise((resolve, reject) => {
    try {
      // 检查token是否过期
      if (isTokenExpired()) {
        refreshToken().then(function() {
          // 重新发起请求
          request(options).then(resolve).catch(reject);
        }).catch(function(error) {
          // 刷新失败，跳转到登录页
          wx.showModal({
            title: '登录已过期',
            content: '请重新登录',
            showCancel: false,
            success: function() {
              wx.redirectTo({
                url: '/pages/login-1/login-1'
              });
            }
          });
          reject(error);
        });
        return;
      }

      const accessToken = getAccessToken();
      
      wx.request({
        url: BASE_URL + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'content-type': 'application/json',
          'Authorization': 'Bearer ' + accessToken,
          ...options.header
        },
        success: function(res) {
          // 处理响应
          if (res.statusCode === 200 || res.statusCode === 201){
            resolve(res.data);
          } else if (res.statusCode === 401) {
            // 未授权，尝试刷新token
            refreshToken().then(function() {
              // 重新发起请求
              request(options).then(resolve).catch(reject);
            }).catch(function() {
              wx.showModal({
                title: '登录已过期',
                content: '请重新登录',
                showCancel: false,
                success: function() {
                  wx.redirectTo({
                    url: '/pages/login-1/login-1'
                  });
                }
              });
              reject(new Error('Unauthorized'));
            });
          } else {
            reject(new Error(`HTTP ${res.statusCode}`));
          }
        },
        fail: function(error) {
          reject(error);
        }
      });
    } catch (error) {
      reject(error);
    }
  });
}

// 登录函数
function login(identifier, password) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + '/api/login/password',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        identifier: identifier,
        password: password
      },
      success: function(res) {
        if (res.data.code === 200) {
          // 保存token
          wx.setStorageSync('access_token', res.data.data.access_token);
          wx.setStorageSync('refresh_token', res.data.data.refresh_token);
          resolve(res.data);
        } else {
          reject(new Error(res.data.msg || '登录失败'));
        }
      },
      fail: function(error) {
        reject(error);
      }
    });
  });
}

// 注册函数
function register(phone, password, nickname) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + '/api/register/submit',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        phone: phone,
        password: password,
        nickname: nickname
      },
      success: function(res) {
        resolve(res.data);
      },
      fail: function(error) {
        reject(error);
      }
    });
  });
}

// 获取用户信息
function getUserInfo() {
  return request({
    url: '/api/profile',
    method: 'GET'
  }).then(res => {
    console.log('获取用户信息响应:', res);
    if (res.code === 200 && res.data && res.data.avatar_url) {
      console.log('原始头像URL:', res.data.avatar_url);
      
      // 如果已经是完整URL，直接返回
      if (res.data.avatar_url.startsWith('http')) {
        console.log('已经是完整URL，无需处理');
      } else {
        // 检测并去除重复的static/avatar/
        let processedUrl = res.data.avatar_url;
        
        // 如果包含重复的static/avatar/static/avatar/
        if (processedUrl.includes('static/avatar/static/avatar/')) {
          processedUrl = processedUrl.replace('static/avatar/static/avatar/', 'static/avatar/');
          console.log('检测到重复路径，已去除重复部分');
        }
        // 去掉开头的斜杠，然后拼接BASE_URL
        const cleanUrl = processedUrl.replace(/^\/+/, '');
        res.data.avatar_url = BASE_URL + '/' + cleanUrl;
        console.log('处理后的头像URL:', res.data.avatar_url);
      }
    }
    return res;
  });
}

// 更新用户资料
function updateProfile(data) {
  return request({
    url: '/api/profile',
    method: 'PUT',
    data: data
  });
}

// 上传头像
function uploadAvatar(filePath) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: BASE_URL + '/api/upload_avatar',
      filePath: filePath,
      name: 'avatar',
      header: {
        'Authorization': 'Bearer ' + getAccessToken()
      },
      success: (res) => {
        resolve(JSON.parse(res.data));
      },
      fail: reject
    });
  });
}

// 启动会话
function startConversation(persona) {
  return request({
    url: '/api/start_conversation',
    method: 'POST',
    data: {
      persona: persona
    }
  });
}

// 获取会话历史
function getConversationHistory(page, perPage) {
  return request({
    url: '/api/conversation/history',
    method: 'GET',
    data: {
      page: page || 1,
      per_page: perPage || 5
    }
  });
}

// 获取情绪日历数据
function getEmotionCalendar(year, month) {
  return request({
    url: '/api/emotion/calendar',
    method: 'GET',
    data: {
      year: year,
      month: month
    }
  });
}

function getConversationDetail(conversationId) {
  return request({
    url: `/api/conversation/${conversationId}`,
    method: 'GET'
  });
}

// 获取指定日期的情绪记录
function getEmotionRecordsByDate(date) {
  return request({
    url: '/api/emotion/querybydate',
    method: 'GET',
    data: {
      date: date
    }
  });
}

// 获取情绪记录详情
function getEmotionRecordDetail(recordId) {
  return request({
    url: '/api/emotion/querybyid',
    method: 'GET',
    data: {
      record_id: recordId
    }
  });
}

// 上传情绪记录
function uploadEmotionRecord(data) {
  return request({
    url: '/api/emotion/upload',
    method: 'POST',
    data: data
  });
}

// 获取情绪记录（按月）
function getEmotionRecordsByMonth(year, month) {
  return request({
    url: '/api/emotion/querybymonth',
    method: 'GET',
    data: {
      year: year,
      month: month
    }
  });
}

// 获取情绪记录（分页）
function getEmotionRecordsByPage(page, perPage) {
  return request({
    url: '/api/emotion/querybypage',
    method: 'GET',
    data: {
      page: page || 1,
      per_page: perPage || 5
    }
  });
}

// 提交心理测评
function submitTest(testType, answers) {
  return request({
    url: '/api/test/' + testType,
    method: 'POST',
    data: {
      answers: answers
    }
  });
}

// 获取默认用户头像
function getDefaultUserAvatar() {
  return BASE_URL + '/static/avatar/default_avatar.png';
}

// 发送消息（支持图片和语音）
function sendMessage(conversationId, message, imageBase64 = null, audioBase64 = null) {
  const data = {
    message: message,
    conversation_id: conversationId
  };
  
  if (imageBase64) {
    data.image_base64 = imageBase64;
  }
  
  if (audioBase64) {
    data.audio = audioBase64;
    data.filename = 'audio.mp3';
    data.content_type = 'audio/mpeg';
  }
  
  return request({
    url: '/api/conversation',
    method: 'POST',
    data: data
  });
}



// 切换人设
function switchPersona(conversationId, persona) {
  return request({
    url: '/api/conversation/switch_persona',
    method: 'POST',
    data: {
      conversation_id: conversationId,
      persona: persona
    }
  });
}

// 从对话记录情绪
function recordEmotionFromConversation(data) {
  return request({
    url: '/api/emotion/conversation',
    method: 'POST',
    data: data
  });
}

module.exports = { 
  request, 
  login, 
  register, 
  getUserInfo, 
  updateProfile, 
  uploadAvatar,
  startConversation,
  sendMessage,
  getConversationHistory,
  getEmotionCalendar,
  getEmotionRecordsByDate,
  getEmotionRecordDetail,
  uploadEmotionRecord,
  getEmotionRecordsByMonth,
  getEmotionRecordsByPage,
  submitTest,
  getAccessToken,
  getRefreshToken,
  refreshToken,
  getDefaultUserAvatar,
  getConversationDetail,
  switchPersona,
  recordEmotionFromConversation
}; 